package main

import (
	"gitee.com/vesmr/websockethttp-go"
	"log"
	"net/http"
	"strconv"
)

func requestHandlerFunc(context *websockethttp.SocketContext) {
	header := make(map[string]string)
	header["name"] = context.Channel.Name
	for name, channel := range context.GetConnChannelMap() {
		channel.SendRequestMessage(&websockethttp.SocketRequest{
			Uid:     websockethttp.NewMessageId(),
			Handler: "Default",
			Method:  "Default",
			Header:  header,
			Body:    context.Request.Body,
			Sign:    "none",
		}, func(response *websockethttp.SocketResponse) {
			log.Printf("message_delivery_result -> name: %v Code: %v", name, response.Code)
		})
	}
}

func onlineUsers(context *websockethttp.SocketContext) {
	context.Response.Code = 0
	context.Response.Msg = "success"
	context.Response.Body = strconv.Itoa(len(context.Serv.GetConnChannelMap()))
}

func main() {
	server := websockethttp.CreateServer()
	server.SetConnMonitorFunc(func(channel *websockethttp.ConnChannel) {
		log.Printf("websocket_http_received_connection -> channelName: %v", channel.Name)
	})
	server.SetAuthorizationFunc(func(request *http.Request) (string, bool) {
		name := request.URL.Query().Get("name")
		if len(name) > 0 && len(name) <= 64 {
			return name, true
		} else {
			return "", false
		}
	})

	server.RegisterRequestHandlerFunc("Default", "Default", requestHandlerFunc)
	server.RegisterRequestHandlerFunc("Number", "Count", onlineUsers)

	http.HandleFunc("/websocket/http", func(writer http.ResponseWriter, request *http.Request) {
		server.Launcher(writer, request)
	})
	http.HandleFunc("/health/index", func(writer http.ResponseWriter, request *http.Request) {
		log.Printf("websocket_http_health_index: host: %v", request.URL.Host)
		writer.WriteHeader(200)
		_, _ = writer.Write([]byte("ok"))
	})
	_ = http.ListenAndServe(":"+strconv.Itoa(1001), nil)
}
